package deviceScript

import (
	"errors"
	"fmt"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Method"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEntity"
	"go-fox-edge-device/deviceLogger"
)

type reportService struct {
}

func (e *reportService) Decode(routineKey string, manufacturer string, deviceType string, operateEntityList []*edgeEntity.OperateEntity, recv interface{}, params map[string]interface{}) (rnt map[string]interface{}, err error) {
	// 定义一个最终的异常拦截，用来防止可能的代码BUG
	defer func() {
		if r := recover(); r != nil {
			message := fmt.Sprintf("reportService.Decode() 捕获到异常:%v", r)
			err = errors.New(message)
			deviceLogger.PrintLogger(message)
		}
	}()

	deviceLogger.PrintLogger(fmt.Sprintf("接收到通道上报数据：\n%v", recv))

	// 取出ScriptEngine
	engine := engineService.getScriptEngine(manufacturer, deviceType, routineKey)

	// 为ScriptEngine填入全局变量
	err = engineOperator.setRecvEnvValue(engine, recv, params)
	if err != nil {
		return nil, err
	}

	for _, operateEntity := range operateEntityList {
		// 取出：解码信息
		decode := Map.GetOrDefault(operateEntity.EngineParam, "decode", make(map[string]interface{}))
		if Method.HasEmpty(decode) {
			return nil, errors.New("找不到对应操作名称的解码函数：" + operateEntity.OperateName)
		}

		// 解码脚本
		decodeMain := Map.GetOrDefault(decode.(map[string]interface{}), "main", "").(string)
		decodeScript := Map.GetOrDefault(decode.(map[string]interface{}), "code", "").(string)
		if Method.HasEmpty(decodeMain, decodeScript) {
			return nil, errors.New("找不到对应操作名称的解码函数：" + operateEntity.OperateName)
		}

		// 将解码结果，根据模式，用各自的字段带回
		if EnumRecord == operateEntity.DataType {
			return engineOperator.decodeRecord(engine, operateEntity.OperateName, decodeMain, decodeScript)
		} else if EnumResult == operateEntity.DataType {
			return engineOperator.decodeResult(engine, operateEntity.OperateName, decodeMain, decodeScript)
		} else {
			return engineOperator.decodeStatus(engine, operateEntity.OperateName, decodeMain, decodeScript)
		}
	}

	return nil, errors.New("找不到对应的解码器！")
}
